/**
 * 
 */
package systole.persistence.brokersDB;

import java.util.List;
import org.hibernate.Criteria;

import org.hibernate.HibernateException;
import org.hibernate.Session;

import org.hibernate.criterion.Restrictions;
import systole.domain.clinicalInformation.Medicine;
import systole.exceptions.ExceptionDAO;
import systole.persistence.FacadeDB;
import systole.persistence.brokersInterface.MedicineBroker;
import systole.view.messages.ErrorMessages;

/**
 * @author jmj
 *
 */
public class MedicineBrokerDB extends BrokerDB implements MedicineBroker {

    /**
     */
    public MedicineBrokerDB() {
        super();
    }

    /* (non-Javadoc)
     * @see systole.persistence.brokersInterface.MedicineBroker#getAllMedicines()
     */
    @Override
    public List<Medicine> getAllMedicines() throws ExceptionDAO {
        try {
            this.logger.logDebug("Getting all medicines");
            Session currentSession = FacadeDB.getInstance().getCurrentSession();   
            List<Medicine> medicines = currentSession.createQuery("from Medicine m order by upper(m.name)").list();
            this.logger.logDebug("get medicines successfully");
            return medicines;
        } catch (HibernateException e) {
            this.logger.logError("error on get medicines, msg: " + e.getMessage());
            throw new ExceptionDAO("No se pudieron obtener los medicamentos", e.fillInStackTrace());
        }
    }
    /* (non-Javadoc)
     * @see systole.persistence.brokersInterface.MedicineBroker#insert(systole.domain.clinicalInformation.Medicine)
     */

    @Override
    public void insert(Medicine medicine) throws ExceptionDAO {
        try {
            this.logger.logDebug("saving medicine");
            Session currentSession = FacadeDB.getInstance().getCurrentSession();
            currentSession.save(medicine);
            this.logger.logDebug("save medicine successfully");
        } catch (HibernateException e) {
            this.logger.logError("error on save medicines, msg: " + e.getMessage());
            throw new ExceptionDAO(ErrorMessages.CHANGES_NOT_SAVE, e.fillInStackTrace());
        }
    }

    /* (non-Javadoc)
     * @see systole.persistence.brokersInterface.MedicineBroker#update(systole.domain.clinicalInformation.Medicine)
     */
    @Override
    public void update(Medicine medicine) throws ExceptionDAO {
        try {
            this.logger.logDebug("updating medicine");
            Session currentSession = FacadeDB.getInstance().getCurrentSession();
            currentSession.update(medicine);
            this.logger.logDebug("update medicine successfully");
        } catch (HibernateException e) {
            this.logger.logError("error on update medicines, msg: " + e.getMessage());
            throw new ExceptionDAO(ErrorMessages.CHANGES_NOT_SAVE, e.fillInStackTrace());
        }
    }

    @SuppressWarnings("unchecked")
    public boolean existMedicine(String name, Integer id) throws ExceptionDAO {
        try {
            this.logger.logDebug("exist Medicine");
            Session currentSession = FacadeDB.getInstance().getCurrentSession();
            Criteria criteria = currentSession.createCriteria(Medicine.class).
                    add((id == null) ? Restrictions.eq("name", name)
                    : Restrictions.and(Restrictions.eq("name", name), Restrictions.ne("id", id)));
            List list = criteria.list();
            this.logger.logDebug("exist Medicine successfully");
            return !list.isEmpty();
        } catch (HibernateException e) {
            this.logger.logError("error on exist Medicine, msg: " + e.getMessage());
            throw new ExceptionDAO("No se pudo verificar si ya existe la medicación", e.fillInStackTrace());
        }
    }

    public Medicine getMedicineByName(String name) throws ExceptionDAO {
        try {
            this.logger.logDebug("get Medicine by name");
            Session currentSession = FacadeDB.getInstance().getCurrentSession();
            Criteria criteria = currentSession.createCriteria(Medicine.class).
                    add(Restrictions.eq("name", name)).setMaxResults(1);
            return (Medicine) criteria.uniqueResult();
        } catch (HibernateException e) {
            this.logger.logError("error on get Medicine by name, msg: " + e.getMessage());
            throw new ExceptionDAO("No se pudo obtener la medicación", e.fillInStackTrace());
        }
    }
}
